package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.together.TogetherJobExam;
import com.zbkj.service.dao.TogetherJobExamDao;
import com.zbkj.service.service.TogetherJobExamService;
import com.zbkj.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;

@Service
public class TogetherJobExamServiceImpl extends ServiceImpl<TogetherJobExamDao, TogetherJobExam> implements TogetherJobExamService {

    @Resource
    private TogetherJobExamDao dao;

    @Autowired
    private UserService userService;

    @Override
    public TogetherJobExam getByDUid(Integer uid1, Integer uid2) {
        return dao.getByDUid(uid1,uid2);
    }

    @Override
    public String handle(TogetherJobExam request) {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<TogetherJobExam> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TogetherJobExam::getIsDel,0);
        lqw.eq(TogetherJobExam::getStatus,0);
        lqw.eq(TogetherJobExam::getId,request.getId());
        TogetherJobExam togetherJobExam = getOne(lqw);
        if(ObjectUtil.isNull(togetherJobExam))
            throw new CrmebException("查无此试稿");

        if(!Objects.equals(userId, togetherJobExam.getUid()))
            throw new CrmebException("试稿数据非法");

        switch (request.getAction()){
            case 1:
                togetherJobExam.setStatus(1);
                break;
            case 0:
                togetherJobExam.setIsDel(true);
                break;
        }
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算日期
        LocalDate dateAfter30Days = currentDate.plusDays(togetherJobExam.getLimitNum());
        // 将LocalDate转换为Date
        Date date = Date.from(dateAfter30Days.atStartOfDay(ZoneId.systemDefault()).toInstant());

        togetherJobExam.setLimitTime(date);
        updateById(togetherJobExam);

        return "试稿状态更新成功";
    }
}
